<!-- eslint-disable vue/max-attributes-per-line -->
<template>
  <div class="bianryBox">
    <div class="buttonBox">
      <div class="SecondRow">
        <div class="secondLeft">
          <el-button
            size="primary"
            @click="showDialog('dialog1')"
            class="xinbtn"
          >
            添加分类
          </el-button>
        </div>
        <div class="secondRight">
          <el-button circle icon="el-icon-refresh-right" @click="refreshList">
          </el-button>
        </div>
      </div>
    </div>

    <!-- 新增弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <span>
        <el-form
          ref="ruleForm"
          :label-position="labelPosition"
          :model="ruleForm"
          :rules="rules"
          class="demo-ruleForm"
          label-width="100px"
        >
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="ruleForm.categoryName"></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="ruleForm.sort"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="categoryDescription">
            <el-input v-model="ruleForm.categoryDescription"></el-input>
          </el-form-item>
          <el-form-item label="分类图片">
            <el-upload
              ref="fileUploadRef"
              class="upload-demo filter-item"
              drag
              :action="uploadURL"
              :before-upload="beforeHandleSuccess"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :on-progress="onProgress"
              :show-file-list="true"
              :multiple="false"
            >
              <img v-if="fileUrl" :src="fileUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">最大可上传10M的文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </span>
    </el-dialog>
    <!-- 编辑弹框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible_two"
      width="30%"
    >
      <span>
        <el-form
          ref="ruleFormTwo"
          :label-position="labelPosition"
          :model="ruleFormTwo"
          :rules="rules"
          class="demo-ruleForm"
          label-width="100px"
        >
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="ruleFormTwo.categoryName"></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="ruleFormTwo.sort"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="categoryDescription">
            <el-input v-model="ruleFormTwo.categoryDescription"></el-input>
          </el-form-item>
          <el-form-item label="分类图片">
            <el-upload
              ref="fileUploadRef"
              class="upload-demo filter-item"
              drag
              :action="uploadURL"
              :before-upload="beforeHandleSuccess"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :on-progress="onProgress"
              :show-file-list="true"
              :multiple="false"
            >
              <img v-if="fileUrl" :src="fileUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">最大可上传10M的文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_two = false">取 消</el-button>
        <el-button type="primary" @click="submitForm_two">提交</el-button>
      </span>
    </el-dialog>
    <div class="DataTableDiv">
      <el-table
        v-loading="loading"
        v-model="ruleForm"
        :data="getShopLists"
        :header-cell-style="headerCellStyle"
        :tree-props="{
          children: 'categoryDTOList',
          hasChildren: 'hasChildren',
        }"
        border
        row-key="id"
        style="width: 100%; margin-bottom: 20px"
      >
        <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
        <el-table-column
          align="center"
          label="分类名称"
          prop="categoryName"
          min-width="350"
        >
          <template slot-scope="{ row }">
            <p>{{ row.categoryName }}</p>
          </template>
        </el-table-column>
        <el-table-column align="center" label="排序" prop="sort" min-width="100">
          <template slot-scope="{ row }">
            <p>{{ row.sort }}</p>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="服务费率"> </el-table-column> -->
        <el-table-column align="center" label="分类图片" prop="categoryPhoto">
          <template slot-scope="{ row }">
            <img
              :src="row.categoryPhoto"
              alt=""
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否显示" prop="address">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isEnabled == 1"
              active-color="#1289FF"
              inactive-color="#ccc"
              @change="handleSwitchChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" min-width="200">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="lookShop(scope.row)"
              >查看
            </el-button>
            <template>
              <el-button
                v-if="scope.row.categoryDTOList"
                size="small"
                type="text"
                @click="showDialog(scope.row)"
                >新增下级
              </el-button>
            </template>
            <el-button size="small" type="text" @click="putShop(scope.row)"
              >编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line import/no-cycle
import {
  getCategoryShop,
  addCategoryShop,
  putCategoryShop,
} from "@/api/mallApi/categoryShop/categoryShop";

import { cloud } from "@/framework/utils/request";
import { getToken } from "@/framework/utils/auth";
export default {
  name: "BinaryTree",
  data() {
    return {
      parentId: 0,
      loading: true,
      // isEnabled: 0,
      dialogVisible: false,
      dialogVisible_two: false,
      dialogTitle: "",
      switchValue: false,
      getShopLists: [],
      labelPosition: "right",
      uploadLoading: false,
      fileUploadVisible: false,
      fileUrl: "",
      categoryName: "",
      categoryDescription: "",
      sort: "",
      ruleForm: {
        parentId: 0,
        id: null,
        categoryName: null,
        categoryDescription: null,
        sort: null,
        categoryPhoto: null,
      },
      ruleFormTwo: {
        parentId: 0,
        id: null,
        categoryName: null,
        categoryDescription: null,
        sort: null,
        categoryPhoto: null,
      },
      rules: {
        categoryName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
        categoryDescription: [
          { required: true, message: "请输入描述", trigger: "blur" },
        ],
      },
      uploadURL:
        process.env.VUE_APP_BASE_API +
        cloud.file +
        "/sysFileInfo/upload?secretFlag=N&fileBucket=mall",
      // uplaodHeaders: {
      //   Authorization: getToken(),
      // },
    };
  },

  mounted() {
    this.getShopList();
  },

  methods: {
    resetForm(formName) {
      console.log(this.$refs[formName], " this.$refs[formName]");
      this.$refs[formName].resetFields();
    },
    handleSwitchChange(row) {
      var ruleForm = {};
      ruleForm.id = row.id;
      ruleForm.isEnabled = row.isEnabled == 0 ? 1 : 0;
      putCategoryShop(ruleForm).then((response) => {
        this.$dtModal.msgSuccess("修改成功");
        this.getShopList();
      });
    },
    headerCellStyle({ column }) {
      if (column.label === "分类名称") {
        return { background: "#f8f8f8", color: "#2b2b2b" };
      } else if (column.label === "排序") {
        return { background: "#f8f8f8", color: "#2b2b2b" };
      } else if (column.label === "服务费率") {
        return { background: "#f8f8f8", color: "#2b2b2b" };
      } else if (column.label === "分类图片") {
        return { background: "#f8f8f8", color: "#2b2b2b" };
      } else if (column.label === "是否显示") {
        return { background: "#f8f8f8", color: "#2b2b2b" };
      } else if (column.label === "操作") {
        return { background: "#f8f8f8", color: "#2b2b2b" };
      }
    },
    showDialog(dialog) {
      if (dialog === "dialog1") {
        this.dialogTitle = "新增";
        this.parentId = 0;
        this.fileUrl = "";
      } else {
        this.dialogTitle = "新增下级";
        this.parentId = dialog.id;
        this.fileUrl = "";
      }
      this.dialogVisible = true;
      const that = this;
      this.$nextTick(() => {
        console.log("11111新增");
        that.ruleForm.categoryName = "";
        that.ruleForm.categoryDescription = "";
        that.ruleForm.sort = "";
        that.resetForm("ruleForm");
      });
    },
    baseURL() {
      return process.env.VUE_APP_BASE_API + cloud.file;
    },

    beforeHandleSuccess(file) {
      const isLt10M = file.size / 1024 / 1024 <= 10;
      if (!isLt10M) {
        this.$message.error(
          "您上传文件超过系统限制的最大值，最大可上传10M的文件!"
        );
        return false;
      }
      if (file.name.length > 50) {
        this.$message.error("文件名称过长，建议长度在50字符内!");
        return false;
      }
      return true;
    },
    uploadSuccess(response, file, fileList) {
      this.uploadLoading = false;
      this.$dtMessage({
        title: "成功",
        message: "上传成功",
        type: "success",
        duration: 2000,
      });
      this.fileUrl = response.data.fileUrl;
      this.fileUploadVisible = false;
      this.getShopList();
    },
    uploadError(err, file, fileList) {
      this.uploadLoading = false;
      this.$message.error(err);
    },
    onProgress(event, file, fileList) {
      this.uploadLoading = true;
    },
    // 新增提交
    submitForm() {
      // 提交表单操作
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.ruleForm.parentId = this.parentId;
          this.ruleForm.categoryPhoto = this.fileUrl;
          // this.ruleForm.requestType = this.requestType;
          console.log("123", this.ruleForm);
          addCategoryShop(this.ruleForm).then((response) => {
            this.$dtModal.msgSuccess("新增成功");
            this.dialogVisible = false;
            this.getShopList();
          });
        }
      });
    },
    // 修改提交
    submitForm_two() {
      this.ruleFormTwo.categoryPhoto = this.fileUrl;
      this.$refs.ruleFormTwo.validate((valid) => {
        if (valid) {
          let that = this;
          that.$dtModal
            .confirm("是否确认修改")
            .then(function () {
              putCategoryShop(that.ruleFormTwo).then((response) => {
                that.$dtModal.msgSuccess("修改成功");
                that.dialogVisible_two = false;
                that.getShopList();
              });
            })
            .catch(() => {});
        }
      });
    },
    //获取数据
    getShopList() {
      getCategoryShop().then((res) => {
        this.getShopLists = res.data;
        this.loading = false;
      });
    },
    // 查看
    lookShop(row) {
      this.ruleFormTwo = JSON.parse(JSON.stringify(row));
      this.categoryName = this.ruleFormTwo.categoryName;
      this.categoryDescription = this.ruleFormTwo.categoryDescription;
      this.categoryPhoto = this.ruleFormTwo.categoryPhoto;
      this.sort = this.ruleFormTwo.sort;
      this.fileUrl = row.categoryPhoto;

      this.dialogVisible_two = true;
    },
    //编辑数据
    putShop(row) {
      this.ruleFormTwo = JSON.parse(JSON.stringify(row));
      this.categoryName = this.ruleFormTwo.categoryName;
      this.categoryDescription = this.ruleFormTwo.categoryDescription;
      this.categoryPhoto = this.ruleFormTwo.categoryPhoto;
      this.sort = this.ruleFormTwo.sort;
      this.fileUrl = row.categoryPhoto;
      this.dialogVisible_two = true;
    },
    //刷新页面
    refreshList() {
      location.reload();
      this.getShopList();
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
::v-deep .cell {
  display: flex;
  justify-content: center;
}
::v-deep .el-table__expand-icon {
  margin-top: 13px;
}
::v-deep .el-upload-dragger {
  width: 175px;
  height: 175px;
}
.bianryBox {
  width: 98%;
  min-height: 750px;
  margin-top: 1%;
  margin-bottom: 1%;
  margin-left: 1%;
  background-color: #fff;
  overflow: hidden;
}
.buttonBox {
  width: 100%;
  height: 80px;
  display: flex;
  .SecondRow {
    width: 100%;
    height: 80px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    margin-top: 30px;
    .secondLeft {
      margin-left: 32px;
    }
    .secondRight {
      margin-right: 32px;
    }
  }
}
.DataTableDiv {
  width: 98%;
  height: auto;
  margin-left: 1%;
}
</style>
